import axios from "axios";
import store from "@/store";
import { Loading } from "element-ui";
import { tansParams, blobValidate } from "@/utils/ruoyi";
import errorCode from "@/utils/errorCode";
let downloadLoadingInstance;
axios.defaults.headers["Content-Type"] = "application/json;charset=utf-8";
const service = axios.create({
  baseURL: store.state.global.httpServer,

  // 超时
  timeout: 10000
});

//拦截axios 请求 是否有存储token 有的话 设置axios的header
service.interceptors.request.use(
  config => {
    let token = localStorage.getItem("accessToken");
    if (token) {
      config.headers.accessToken = token;
    }
    // console.log(config.apiMode);
    // // get请求映射params参数
    if (config.method === 'get' && config.params && config.apiMode  === 'baseSetting') {
      let url = config.url + '?' + tansParams(config.params);
      url = url.slice(0, -1);
      config.params = {};
      config.url = url;
    }

    return config;
  },
  error => {
    console.log(error);
    return Promise.reject();
  }
);
service.interceptors.response.use(
  response => {
    if (response.status === 200) {
      return response.data;
    } else {
      Promise.reject();
    }
  },
  error => {
    console.log(error);
    return Promise.reject();
  }
);

// 通用下载方法
export function download(url, params, filename) {
  downloadLoadingInstance = Loading.service({
    text: "正在下载数据，请稍候",
    spinner: "el-icon-loading",
    background: "rgba(0, 0, 0, 0.7)"
  });
  return service
    .post(url, params, {
      transformRequest: [
        params => {
          return tansParams(params);
        }
      ],
      headers: { "Content-Type": "application/x-www-form-urlencoded" },
      responseType: "blob"
    })
    .then(async data => {
      const isLogin = await blobValidate(data);
      if (isLogin) {
        const blob = new Blob([data]);
        saveAs(blob, filename);
      } else {
        const resText = await data.text();
        const rspObj = JSON.parse(resText);
        const errMsg =
          errorCode[rspObj.code] || rspObj.msg || errorCode["default"];
        Message.error(errMsg);
      }
      downloadLoadingInstance.close();
    })
    .catch(r => {
      console.error(r);
      Message.error("下载文件出现错误，请联系管理员！");
      downloadLoadingInstance.close();
    });
}
export default service;
